{% extends 'base.html' %}

{% block title %}Reading &quot;{{ html_title }}&quot;{% endblock %}

{% block body %}

<script type="text/javascript" src="{{ url_for('static', filename='js/player.js') }}" charset="utf-8" defer></script>
<script type="text/javascript" src="{{ url_for('static', filename='js/resize.js') }}" charset="utf-8" defer></script>
<script type="text/javascript" src="{{ url_for('static', filename='js/text-options.js') }}" charset="utf-8" defer></script>
<script type="text/javascript" src="{{ url_for('static', filename='js/dict-tabs.js') }}" charset="utf-8"></script>

<div id="rendering_controls" style="display: none">
  <pre>
    lang_is_rtl: <input id="lang_is_rtl" value="{{ is_rtl }}">
    book_id: <input id="book_id" value="{{ book.id }}">
    book_audio: <input id="book_audio_file" value="{{ book.audio_filename or '' }}">
    book_audio_current_pos: <input id="book_audio_current_pos" value="{{ book.audio_current_pos or 0 }}">
    book_audio_bookmarks: <input id="book_audio_bookmarks" value="{{ book.audio_bookmarks or '' }}">
    page_num: <input id="page_num" value="{{ page_num }}">
    page_count: <input id="page_count" value="{{ page_count }}">
    highlights: <span id="show_highlights">{{ show_highlights|lower }}</span>
    track_page_open: <input id="track_page_open" value="{{ track_page_open|lower }}">
  </pre>
</div>

<script>
  // The sentence dictionaries configured for the language.  This var
  // is used in lute.js.
  var LUTE_SENTENCE_LOOKUP_URIS = {{ sentence_dict_uris|safe }};
</script>


<div id="read_pane_container">

<div id="read_pane_left">

  <div id="reading_menu">
    {% include "read/reading_menu.html" %}
  </div>

  <div id="reading-header">

    <div class="reading_header_container">
        <div class="reading_header_left">
          <div class="hamburger-btn" onclick="toggleMenu()">
            <span class="hamburger"></span>
            <span class="hamburger"></span>
            <span class="hamburger"></span>
          </div>
	  <a href="/">
		<img
		  src="{{ url_for('static', filename='img/lute.png') }}"
		  class="lutelogo_small"
		  style="cursor: pointer"
		  title="Home"
		/>
	  </a>
        </div>
        <div class="reading_header_mid">
        <div class="reading_header_mid_top">
          <div class="texttitlecontainer">
            <h1 id="headertexttitle" {% if is_rtl %}dir="rtl" {% endif %} class="hide">{{ book.title }}</h1>
          </div>
          <div class="reading_header_page">
            <!-- <a id="reading_home_link" class="home-link" href="/">Home</a> -->
            <div class="read-bookmark-buttons-container">
              <button id="read-bkm-save-btn" class="read-bkm-btn"></button>
              <!-- <div class="read-bookmark-jump-container"> -->
                <!-- <button id="read-bkm-prev-btn" class="read-bkm-btn"></button> -->
                <!-- <button id="read-bkm-next-btn" class="read-bkm-btn"></button> -->
              <!-- </div> -->
            </div>
            <div id="page_indicator">{{ page_num }}/{{ page_count }}</div>
          </div>
          </div>
          <div class="read-slide-container">
            <div class="read_page_nav read_page_disabled"
              id="navPrev"
              onclick="goto_relative_page(-1)">◀</div>
            <input type="range" id="read-slider" class="read_page_disabled" max="{{ page_count - 1 }}" value="{{ page_num }}" step="1">
            <div class="read_page_nav read_page_disabled"
              id="navNext"
              onclick="goto_relative_page(1)">▶</div>
          </div>
        </div>
    </div>

    <!-- <div class="definition-container"></div> -->

  </div>

  {% include "read/audio_player.html" %}

  <h1 id="thetexttitle" {% if is_rtl %}dir="rtl" {% endif %} class="hide">{{ book.title }}</h1>
  <div id="thetext" {% if is_rtl %}dir="rtl" {% endif %}>
    ...
  </div>

  <div id="reading-footer" style="text-align: center">
    <p>
      <span
        id="footerMarkRestAsKnownNextPage"
        style="cursor: pointer; color: #4CBB17;"
        onclick="handle_page_done(true, 1)"
        title="Mark rest as known, mark page as read, then go to next page">
        &#x2714;
      </span>

      <span
        id="footerNextPage"
        style="cursor: pointer; font-size: 1.5em; font-weight: bold;"
        onclick="handle_page_done(false, 1)"
        title="Mark page as read, then go to next page">
        &#8250;
      </span>
    </p>

    <div id="final_page_controls" class="hide">
      <p>
        <span
          id="footerMarkRestAsKnown"
          style="cursor: pointer; color: #4CBB17;"
          onclick="handle_page_done(true, 0)"
          title="Mark rest as known, mark page as read">
          &#x2714;
        </span>

        <span
          id="footerDone"
          style="cursor: pointer;"
          onclick="handle_page_done(false, 0)"
          title="Mark page as read">
          &#x2714;
        </span>
      </p>

      <h2>&#127881;</h2>
      <p>
        <a
          href=""
          tabindex="-1"
          onclick="$('#actionposter').submit(); return false;"
          >Archive book</a>
        |
        <a href="/" tabindex="-1">Home</a>
      </p>

      <form
        id="actionposter"
        method="post"
        action="/book/archive/{{ book.id }}"
        ></form>
    </div>

  </div>
  <div class="btm-margin-container"></div>
</div>

<div id="read_pane_right">
  <button class="close-btn read-pane-right-close-btn" onclick="closeRightPane()"></button>
  <div class="wordframecontainer">
  <iframe
    name="wordframe"
    id="wordframeid"
    class="rightreadingframe"
    src="about:blank"
    scrolling="auto"
    style="height: 35%; width: 100%"
    frameborder="0"
  >
    Frame support required.
  </iframe>
  </div>
  <div class="dictcontainer">
    <div id="dicttabs">
      <div id="dicttabslayout"></div>
      <div id="dicttabsstatic"></div>
    </div>
    <div id="dictframes"></div>
  </div>
</div>

</div>

<script>
  LookupButton.LANG_ID = {{ lang_id | safe }};
  LookupButton.TERM_DICTS = {{ term_dicts | safe }};

  let mouseY = 0;
  let scrollY = 0;
  let scrollYBeforeReload = 0;
  const mediaTablet = window.matchMedia("(max-width: 980px)");
  const readPaneRight = document.getElementById("read_pane_right");
  const btmMarginCont = document.querySelector(".btm-margin-container");
  const theText = document.getElementById("thetext");
  const focusChk = document.getElementById("focus");
  const tap_sets_statusChk = document.getElementById("tap_sets_status");

  // Fixes a dev-only "bug" where the right pane doesn't translate up
  // to zero, due to the inline transform property, if it's first
  // opened in mobile view, and the screen is then resized to desktop
  // size.  This handler is only useful during dev: during actual use,
  // the mobile size won't be resized to desktop size.
  mediaTablet.addEventListener("change", function() {
    if (!mediaTablet.matches) {
      readPaneRight.style.removeProperty("transform");
    }
  })

  // Display the term form when a multi-word term is created on
  // mobile. This must be "pointerup", and not "click", because the
  // "touchend" event cancels the click event.
  document.addEventListener("pointerup", (event) => {
      mouseY = event.clientY;
      scrollY = window.scrollY;
  });

  window.addEventListener("scrollend", function(e) {
    scrollYBeforeReload = window.scrollY;
  });

  focusChk.addEventListener("change", () => {
    const book_id = $('#book_id').val();
    readPaneContainer.classList.toggle("focus-mode-active");
    localStorage.setItem(`focusMode-book${book_id}`, `${focusChk.checked}`)
  })

  tap_sets_statusChk.addEventListener("change", () => {
    readPaneContainer.classList.toggle("tap_sets_status-active");
    localStorage.setItem("tap_sets_status", `${tap_sets_statusChk.checked}`)
  })

  let _close_slide_in_menu_on_click_away = function(event) {
    const tgt = event.target;
    if (!tgt.closest("#reading_menu") && !tgt.closest(".hamburger-btn"))
      closeMenu();
    if (!tgt.closest("#read_pane_right") && tgt.parentNode != readPaneRight && !tgt.classList.contains("textitem")) {
      closeRightPane();
    }
  };

  let _lute_form_event_handler = function(event) {
    if (event.data.event === "LuteTermFormOpened") {
      LookupButton.TERM_FORM_CONTAINER = wordFrame.contentDocument.getElementById("term-form-container");
      loadDictionaries();
    }

    if (event.data.event === "LuteTermFormOpened" && mediaTablet.matches) {
      readPaneRight.classList.add("open-dict");
      btmMarginCont.classList.add("open-dict");

      const viewportHeight = document.documentElement.clientHeight;
      const mousePosPercent = mouseY / viewportHeight * 100;
      const dict_transform = `translateY(${Math.round(mousePosPercent) + 10}%)`;
      document.querySelector("#read_pane_right.open-dict").style.transform = dict_transform;
      readPaneRight.style.opacity = "1";

      // Add margin to the bottom of readLeft so it's fully scrollable
      // to the bottom when the dict is over text
      const mt = `calc(${viewportHeight - mouseY + 70}px - var(--player-height))`;
      document.querySelector(".open-dict.btm-margin-container").style.marginTop = mt;

      // Sometimes there's an unnecessary text scroll when clicking on
      // a word. Return to the previous scroll position
      window.scrollTo(0, scrollY);
    }

    // When term form posts data (either updating or deleting terms),
    // reload the full reading screen.
    if (event.data.event === "LuteTermFormPosted") {
      const bookid = $('#book_id').val();
      const pagenum = $('#page_num').val();
      const url = `/read/refresh_page/${bookid}/${pagenum}`;
      const marked = $('.kwordmarked');
      let marked_id = "nomatches"
      if (marked.length != 0) {
        marked_id = $(marked[0]).attr('id');
      }

      // Force remove the old popup.
      // ref https://stackoverflow.com/questions/19266886/tooltip-not-disappearing
      $('div.ui-tooltip').remove();

      $(".dictcontainer").css('display', 'none');

      $('#thetext').load(url, function() {
        const re_marked = $(`#${marked_id}`);
        re_marked.removeClass('kwordmarked');
        re_marked.addClass('wordhover');
      });
    };
  };

  $(document).ready(function () {
    const theTextReloadObs = new MutationObserver((mutationList, observer) => {
      if (scrollYBeforeReload) window.scrollTo(0, scrollYBeforeReload);
    });
    
    theTextReloadObs.observe(theText, {childList: true, subtree: true});

    // do not load focus state if in tablet mode
    if (!mediaTablet.matches) {
      const book_id = $('#book_id').val();
      const focusVal = localStorage.getItem(`focusMode-book${book_id}`);
      if (focusVal === "true") {
        readPaneContainer.classList.add("focus-mode-active");
        focusChk.checked = true;
      }
    }

    if (mediaTablet.matches) {
      if (localStorage.getItem("tap_sets_status") === "true") {
        readPaneContainer.classList.add("tap_sets_status-active");
        tap_sets_statusChk.checked = true;
      }
    }

    createLookupButtons();
    $(document).click(_close_slide_in_menu_on_click_away);

    window.addEventListener("message", _lute_form_event_handler);

    if (have_audio_file()) {
      // Don't actually load the source -- for some reason,
      // the ajax page load was causing the audio src to
      // only load occasionally!  Not sure why.  Source loading
      // is handled in load_player_source().
      $('div.audio-player-container').show();
    }

    goto_relative_page(0, true);
  });

  let have_audio_file = function() {
    return ($('#book_audio_file').val() != '');
  }

  /**
   * Actually set the player source, loading the file,
   * and load all bookmarks etc.
   */
  let load_player_source = function() {
    const book_id = $('#book_id').val();
    // console.log('setting source to ' + `/useraudio/stream/${book_id}`);
    player.src = `/useraudio/stream/${book_id}`;

    t = parseFloat($('#book_audio_current_pos').val());
    player.currentTime = t;
    timeline.value = t;

    bookmarksArray = [];
    bkstring = $('#book_audio_bookmarks').val();
    bks = [];
    if (bkstring != "")
      bks = bkstring.split(';').map((b) => parseFloat(b));
    for (b of bks) {
      bookmarksArray.push(b);
    }

    start_player_post_loop();
  };

  // Set "page X/Y" in page nav.
  let set_page_fraction = function() {
    const pagenum = parseInt($('#page_num').val());
    const maxpage = parseInt($('#page_count').val());
    $('#page_indicator').text(`${pagenum}/${maxpage}`);
  };

  // Enable page nav links, depending on page num.
  let enable_page_nav_links = function() {
    const pagenum = parseInt($('#page_num').val());
    const maxpage = parseInt($('#page_count').val());
    const set_enable = function(el_id, should_enable) {
      const c = 'read_page_disabled';
      if (should_enable)
        $(el_id).removeClass(c);
      else
        $(el_id).addClass(c);
    };
    set_enable('#navPrev', pagenum > 1);
    set_enable('#navNext', pagenum < maxpage);
  };

  // Show/hide footer controls.
  let set_footer_control_visibility = function() {
    const pagenum = parseInt($('#page_num').val());
    const maxpage = parseInt($('#page_count').val());
    if (pagenum == maxpage) {
      $('#final_page_controls').removeClass("hide");
      $('#footerMarkRestAsKnownNextPage').addClass("hide");
      $('#footerNextPage').addClass("hide");
    }
    else {
      $('#final_page_controls').addClass("hide");
      $('#footerMarkRestAsKnownNextPage').removeClass("hide");
      $('#footerNextPage').removeClass("hide");
    }
  };


  let show_hide_title = function(p) {
    const t = $('#thetexttitle');
    const h = $('#headertexttitle');
    if (p == 1) {
      t.removeClass('hide');
      h.addClass('hide');
    }
    else {
      t.addClass('hide');
      h.removeClass('hide');
    }
  };

  // for the reading page return the main container to full width
  document.querySelector(".container").style.cssText = `width: 100%; margin: 0;`;
  
  const readSlider = document.getElementById("read-slider");
  const maxpage = parseInt($('#page_count').val());
  // disable read slider if there's only 1 page
  if (maxpage > 1) document.getElementById("read-slider").classList.remove("read_page_disabled");

  readSlider.addEventListener("input", function() {
    const pagenum = parseInt($('#page_num').val());
    const p = Number(readSlider.value) + 1 - pagenum;
    const actualPage = getActualPage(p);
    updateReadSlider(actualPage);
    document.getElementById("page_indicator").textContent = `${actualPage}/${maxpage}`;
  })
  
  readSlider.addEventListener("change", function() { 
    const pagenum = parseInt($('#page_num').val());
    const p = Number(readSlider.value) + 1 - pagenum;
    goto_relative_page(p);
  })

  function updateReadSlider(p) {
    readSlider.value = p - 1;
    readSlider.style.backgroundSize = `${100 / (maxpage - 1) * readSlider.value}% 100%`;
  }
  
  function getActualPage(p) {
    const pagenum = parseInt($('#page_num').val());
    const m = parseInt($('#page_count').val());
    // console.log(`in getActualPage, pagenum = ${pagenum}`);
    let actualPage = pagenum + p;
    if (actualPage < 1)
      actualPage = 1;
    if (actualPage > m)
      actualPage = maxpage;

    // console.log(`in getActualPage, return actualPage = ${actualPage}`);
    return actualPage;
  }

  /**
   * Go to page relative to that stored in page_num input.
   *
   * On first load of page, initial_page_load is set to true.
   *
   * It appears that for Firefox the player source can't be set
   * while the page content is being ajax'd in.  This makes
   * _NO SENSE AT ALL_ but moving the player source loading
   * to the ajax "success" function worked.  ???
   */
  function goto_relative_page(p, initial_page_load = false) {
    const bookid = $('#book_id').val();
    const actualPage = getActualPage(p);

    updateReadSlider(actualPage);

    let read_action = 'start_reading';
    if ($("#track_page_open").val() == "false")
      read_action = 'refresh_page';
    const url = `/read/${read_action}/${bookid}/${actualPage}`;
    // console.log(`go to page ${url}`);

    $.get(
      url,
      function(data, status) {
        $('#thetext').html(data);
        add_status_classes();
        reset_cursor();
        start_hover_mode();
        $('#page_num').val(actualPage);
        enable_page_nav_links();
        set_page_fraction();
        set_footer_control_visibility();
        show_hide_title(actualPage);
        $("html, body").animate({ scrollTop: 0 });

        if (initial_page_load) {
          prepareTextInteractions();
        }

        // Magic hack for player source to load consistently
        // in Firefox.
        if (initial_page_load && have_audio_file()) {
          load_player_source();
        }
      }
    );
  }

  function closeMenu() {
    $(".reading-menu-sublist.active").removeClass("active");
    $("#reading_menu").removeClass("open-menu");
  }

  function toggleMenu() {
    $("#reading_menu").toggleClass("open-menu");
  }

  function closeRightPane() {
      readPaneRight.classList.remove("open-dict");
      btmMarginCont.classList.remove("open-dict");
      btmMarginCont.style.removeProperty("margin-top");
      readPaneRight.style.removeProperty("transform");
      readPaneRight.style.removeProperty("opacity");
  }

  function edit_current_page() {
    const bookid = $('#book_id').val();
    const pagenum = parseInt($('#page_num').val());
    location.href = `/read/editpage/${bookid}/${pagenum}`;
  }

  // Handle green checkmark in footer.
  function handle_page_done(mark_rest_known = false, next_relative_page = 0) {
    const bookid = $('#book_id').val();
    const pagenum = parseInt($('#page_num').val());
    data = {
      bookid: bookid,
      pagenum: pagenum,
      restknown: mark_rest_known
    };
    $.ajax({
      type: 'post',
      url: '/read/page_done',
      data: JSON.stringify(data),
      contentType: "application/json; charset=utf-8"
    }).done(function(d) {
      goto_relative_page(next_relative_page);
    });
  }

  function add_bookmark() {
    const book_id = document.querySelector('#book_id')?.value;
    const page_num = document.querySelector('#page_num')?.value;
    let title = prompt(`Enter bookmark title, or Cancel to quit`);

    if (!title)
      return;

    fetch(`/bookmarks/add`, {
      method: "POST",
      cache: "no-cache",
      credentials: "same-origin",
      headers: {
        "Content-Type": "application/json"
      },
      body: JSON.stringify({
        title: title,
        book_id: book_id,
        page_num: page_num,
      })
    }).then((resp) => resp.json()).then(json => {
      if (json?.success === true) {
        alert(`Bookmark "${title}" added.`)
      } else {
        alert(`Unable to add bookmark. ${json?.reason || "Unknown reason"}`)
      }
    })
  }

</script>

{% endblock %}
